package com.cyberypower.sjs.jabber2socket;

import com.cyberypower.sjs.common.Config;
import com.cyberypower.sjs.common.ConfigLoader;
import com.cyberypower.sjs.common.Log;
import com.cyberypower.sjs.jabber.JabberAddress;
import com.cyberypower.sjs.jabber.JabberClientSocket;
import com.cyberypower.sjs.jabber.JabberServerSocket;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.ByteBuffer;

public class Jabber2Socket {

    private Logger log = Logger.getLogger(this.getClass());
    private JabberAddress j2sAddress;

    public Jabber2Socket(JabberAddress j2sAddress) {
        this.j2sAddress = j2sAddress;
    }

    private void emph() throws IOException {
        JabberServerSocket jss = new JabberServerSocket(j2sAddress);
        while (true) {
            JabberClientSocket jcs = jss.accept();
            log.info("accepted JABBER connection:" + jcs.getThreadID());
            J2SOne j2SOne = new J2SOne(jcs);
            j2SOne.start();
        }
    }

    class J2SOne extends Thread {
        private JabberClientSocket jcs;


        public J2SOne(JabberClientSocket jsc) {
            this.jcs = jsc;
        }


        public void run() {
            try {
                Socket socket = new Socket(InetAddress.getByName(Config.J2S_HOST), Config.J2S_PORT);
                jcs.setOutput(socket.getOutputStream());
                final byte[] buf = new byte[Config.BUFFER_SIZE];
                try {
                    while (true) {
                        final int len = socket.getInputStream().read(buf);
                        if (len == -1) {
                            jcs.sendText(Config.CLOSE_CONNECTION);
                            break;
                        }
                        if (len > 0)
                            jcs.send(ByteBuffer.wrap(buf, 0, len));
                        else
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] args) {
        Log.init();
        if (args.length < 1) {
            System.out.println("Obligatory option : properties_file");
            System.exit(1);
        }
        ConfigLoader.loadPropertiesJ2S(args[0]);
        Jabber2Socket jabber2Socket = new Jabber2Socket(Config.ADDRESS_J2S);
        try {
            jabber2Socket.emph();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}